package com.lsk.applet;

import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.jfinal.weixin.sdk.utils.HttpUtils;
import com.jfinal.weixin.sdk.utils.JsonUtils;
import com.lsk.admin.order.OrderService;
import com.lsk.admin.shop.ShopServices;
import com.lsk.util.*;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
import java.util.*;

public class AppletController extends Controller {

    static ShopServices shopServices=new ShopServices();
    static AppletService appletService=new AppletService();
    static OrderService orderService=new OrderService();
    Cache cache = Redis.use("ACTIVITYUSER");
    static AppletService txAppletService= Duang.duang(new AppletService());
    /**
     * 小程序通过code换取信息
     */
    public void getSessionKey() {

        String jsCode=getPara("code");

        String shopId=getPara("shopId");

        ApiResult apiResult=appletService.getSessionKeyService(jsCode,shopId);

//        String memberSql="select *from yx_member where openId='"+apiResult.get("openid")+"'";
//
//        Record memberInfo=Db.findFirst(memberSql);
//
//        if (memberInfo==null){
//
//
//            Map<String,String> parMap=new HashMap<>();
//
//            parMap.put("unionid",apiResult.get("openid")+"");
//
//            parMap.put("shopId",shopId);
//
//            appletService.upMemberInfoService(parMap);
//
//            memberInfo=Db.findFirst(memberSql);
//
//        }

        renderJson(apiResult.getJson());
    }

    /**
     * 小程序通过解密信息获取详细信息
     */
    public void decode(){

        String sessionKey=getPara("sessionKey");

        String encryptedData=getPara("encryptedData");
        String ivStr=getPara("ivStr");
        String shopId=getPara("shopId");
        String parentId=getPara("parentId");
        Map resultMap=appletService.decodeService(sessionKey,encryptedData,ivStr,shopId,parentId);
        renderJson(resultMap);

    }

    /**
     * 手机解密
     */
    public void phoneDecode(){

        String encryptedData=getPara("encryptedData");
        String ivStr=getPara("ivStr");

        String sessionKey=getPara("sessionKey");
        Map resultMap=appletService.phoneDecodeService(sessionKey,encryptedData,ivStr);

        renderJson(resultMap);
    }

    /**
     * 保存手机号
     */
    public void saveMemberPhone(){

        String memberId=getPara("memberId");

        String phone=getPara("phone");

        ReturnData returnData=appletService.saveMemberPhoneService(memberId,phone);

        renderJson(returnData);
    }




    /**
     * 门票列表(专区)
     */
    public void ticketList(){
        Map map=getParaMap();
        ReturnData returnData= appletService.ticketListService(map);
        renderJson(returnData);

    }
    /**
     * 类别
     */
    public void ticketList1(){
        Map map=getParaMap();
        ReturnData returnData= appletService.ticketListService1(map);
        renderJson(returnData);

    }



    /**
     * 会员获取奖励
     */
    public void getCoupon(){
        Map map=getParaMap();
        ReturnData returnData=appletService.getCouponService(map);
        renderJson(returnData);
    }

    /**
     * 奖券列表
     */
    public void couponList(){
        String id=getPara("id");
        ReturnData returnData=appletService.couponListService(id);
        renderJson(returnData);
    }
    /**
     * 奖券详情
     */
    public void couponInfo(){

        String couponId=getPara("couponId");
        ReturnData returnData=appletService.couponInfoService(couponId);
        renderJson(returnData);
    }

    /**
     * 奖券核销
     */
    public void couponUse(){

        String couponId=getPara("couponId");

        ReturnData returnData=appletService.couponUseService(couponId);

        renderJson(returnData);
    }
    /**
     * 会员分享
     */
    public void memberShare(){

        String memberId=getPara("memberId");

        appletService.memberShareService(memberId);

    }
    /**
     * 根据会员id获取地址列表
     */
    public void memberAddressList(){

        String memberId=getPara();

        ReturnData returnData=appletService.memberAddressListService(memberId);

        renderJson(returnData);

    }

    /**
     * 保存地址
     */
    public void saveAddress(){

        Map map=getParaMap();

        ReturnData returnData=appletService.saveAddressService(map);

        renderJson(returnData);

    }

    /**
     * 获取会员优惠券
     */
    public void memberCoupon(){

        String memberId=getPara("memberId");

        String state=getPara("state");

        String strPage=getPara("page");

        int page="".equals(strPage)?1:Integer.parseInt(strPage);

        ReturnData returnData= appletService.memberCouponService(memberId,page,state);

        renderJson(returnData);

    }
    /**
     * 根据unionId获取会员id
     */
    public void getMemberInfo(){

        String unionId=getPara("unionId");

        ReturnData returnData=appletService.getMemberInfoService(unionId);

        renderJson(returnData);

    }
    /**
     * 公司详情
     */
    public void shop(){
        String id=getPara("shopId");
        ReturnData returnData=appletService.shopService(id);
        renderJson(returnData);
    }
    /**
     * 成为分销商
     */
    public void memberServoce(){
        Map<String , String []> map=getParaMap();
        ReturnData returnData=appletService.memberServoceService(map);
        renderJson(returnData);
    }
    /**
     * 小程序回调
     */
    public void payCallBack(){

        String xmlStr= HttpKit.readData(getRequest());

        Syslog.info("微信支付成功回调报文为："+xmlStr);
        Map<String,String>  map= PaymentKit.xmlToMap(xmlStr);

        String orderId=map.get("out_trade_no"); //商户订单号

        String transaction_id=map.get("transaction_id");  //微信支付订单号



        Record orderInfo=appletService.getOrderInfoService(orderId);

        Record config=appletService.getWxaConfig(orderInfo.getStr("shopId"));

        boolean checkSign=PaymentKit.verifyNotify(map,config.getStr("payKey") );
        if (checkSign){
            Syslog.info(MD5.md5(xmlStr)+" 支付回调 "+xmlStr);
            appletService.processingOrder(orderId,transaction_id);
//            String result=appletService.payCallBackService(map);
//            renderText(result);
        }else {

            Syslog.error("签名异常："+xmlStr);
            renderNull();
        }
    }

    /**
     * 查看商品详情
     */
    public void findTicketdetail() {
        String id = getPara("id");
        Record record = appletService.findTicketdetail(id);
        renderJson(record);
    }

    //商品规格对应价钱
    public void skuVsmoney(){
        Map<String,String[]> map=getParaMap();
        ReturnData returnData=appletService.skuVsmoney(map);
        renderJson(returnData);
    }

    /**
     * 生成订单
     */
    public void generateorder(){
        Map<String,String[]> map=getParaMap();
        ReturnData returnData=appletService.generateorder(map);
        renderJson(returnData);
    }

    /**
     * 发起支付
     */
    public void orderPay(){

        Map<String,String[]> map=getParaMap();
        ReturnData returnData=appletService.orderPayService(map);
        renderJson(returnData);

    }


    //我的订单
    public void myOrder(){
        String memberId=getPara("memberId");
        ReturnData returnData=appletService.myOrder(memberId);
        renderJson(returnData);
    }

    /**
     * 分类类别
     */
    public void oneClassType(){

        String shopId=getPara("shopId");

        ReturnData returnData=appletService.oneClassTypeService(shopId);

        renderJson(returnData);
    }
    /**
     * 二级类别
     */
    public void twoClassType(){

        String oneClassId=getPara("oneClassId");

        ReturnData returnData=appletService.twoClassTypeService(oneClassId);

        renderJson(returnData);
    }
    /**
     * 首页数据
     */
    public void indexData(){

        String shopId=getPara("shopId");

        ReturnData returnData=appletService.indexDataService(shopId);

        renderJson(returnData);

    }
    /**
     * 热门景点
     */
    public void hotTicket(){

        Map<String,String[]> map=getParaMap();

        ReturnData returnData=appletService.hotTicketService(map);

        renderJson(returnData);

    }
    /**
     * 会员可领取优惠券
     */
    public void waitCoupon(){

        String shopId=getPara("shopId");

        String memberId=getPara("memberId");

        ReturnData returnData=appletService.waitCouponService(memberId,shopId,2);

        renderJson(returnData);

    }

    /**
     * 转发领取优惠券
     */
    public void forwardCoupon(){
        String shopId=getPara("shopId");

        String memberId=getPara("memberId");
//        memberId="e9b00afbb46f02";
        //查询转发可领取的优惠券
        ReturnData returnData=appletService.waitCouponService(memberId,shopId,1);
         List<Record> list=new ArrayList<>();
         if(returnData.isResult()){
             list=(List<Record>) returnData.getData();
         }

         if(list.size()>0){
             for(int i=0;i<list.size();i++){
                 appletService.memberGetCouponService( memberId, String.valueOf(list.get(i).get("id")) , shopId);
             }
         }
         renderJson(returnData);
    }
    /**
     * 会员领取优惠券
     */
    public void memberGetCoupon(){

        String memberId=getPara("memberId");

        String couponId=getPara("couponId");

        String shopId=getPara("shopId");

        ReturnData returnData=appletService.memberGetCouponService( memberId, couponId, shopId);

        renderJson(returnData);

    }

    /**
     * 微信网页授权
     */
    public void wxAuthorization(){

        String shopId=getPara("shopId");

        String memberId=getPara("memberId");

        Record wxConfig=appletService.getWxConfig(shopId);

        String appId=wxConfig.getStr("appId");

        String redirect_uri="https://"+wxConfig.getStr("domain").replace("http://","")

                +"/applet/wxAuthorizationCallBack";

        String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId
                +"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_base" +
                "&state="+memberId+"#wechat_redirect";

        Syslog.info("授权回调域名为:"+url);

        redirect(url);

    }
    /**
     * 公众号授权回调
     */
    public void wxAuthorizationCallBack() {

        String code = getPara("code");

        String memberId = getPara("state");

        Record memberInfo = appletService.getMemberInfoById(memberId);

        String shopId = memberInfo.getStr("shopId");

        Record wxConfig = appletService.getWxConfig(shopId);

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" +

                wxConfig.getStr("appId") + "&secret=" + wxConfig.getStr("appSecret")

                + "&code=" + code + "&grant_type=authorization_code";

        Syslog.info("微信服务号获取openId的url为：" + url);

        String result = HttpKit.get(url);

        Syslog.info("微信服务号获取openId的结果为：" + result);

        Map<String, Object> map = JsonUtil.getMapFromJsonObjStr(result);

        String openId = map.get("openid") + "";
        if ("null".equals(openId) == false) {
            memberInfo.set("payOpenId", openId);

            Db.update("yx_member", "id", memberInfo);
        }
        setAttr("memberInfo", memberInfo);
        setAttr("memberId", memberId);
        renderJsp("apply.jsp");//跳转到申请页
    }
    /**
     * 用户体现，,收到红包
     */
    public void cashWithdrawal(){
        Map<String,String[]> map=getParaMap();

        ReturnData returnData=appletService.cashWithdrawal(map);
        renderJson(returnData);
    }

    /**
     * 领取优惠券
     */
    public void receive(){

        String couponId=getPara("couponId"); //优惠券Id

        String memberId=getPara("memberId"); //会员Id

        String shopId=getPara("shopId");   //店铺Id

        ReturnData returnData=appletService.receive(memberId,couponId,shopId);

        renderJson(returnData);




    }

    //商品分享
    public void shapeTicket() throws Exception {

        String ticketId=getPara("ticketId");//商品id

        String memberId=getPara("memberId");//会员id

        Record ticket=shopServices.findTicketdetail(ticketId);

        String shopId=ticket.get("shopId");

        Record memberInfo=appletService.getMemberInfoById(memberId);
//        String haibaoImg=shop.get("poster");   //海报图片
        String haibaoImg=ticket.get("logo");

        Record record=new Record();

        record.set("ticket",ticket).set("haibaoImg",haibaoImg);



        ImageUtil imageUtil=new ImageUtil();//生成海报

        String versiion=System.currentTimeMillis()+"";
        String result=GlobalParameter.projectPath+"/haibao/"+ticketId+versiion+".jpg";

        String key=haibaoImg+ticket.getStr("name")+"已售"
                +ticket.getStr("salNum")+"原价 "+
                ticket.getStr("originalMoney")+"￥"+
                ticket.getStr("money")+
                memberInfo.getStr("name");

        String cacheResult=cache.get(key);

//        if(cacheResult==null){

            String qrcodeimg=appletService.QrCode(shopId,memberId,ticketId);//小程序码路径

            String shareDecist=" ";

            if ("2".equals(memberInfo.getStr("apply"))){
                shareDecist=memberInfo.getStr("name");

            }

            imageUtil.createPoster(qrcodeimg,haibaoImg,ticket.getStr("name"),
                    "已售"+ticket.getStr("salNum"),
                    "原价 "+ticket.getStr("originalMoney"),
                    "￥"+ticket.getStr("money"),result,shareDecist);
                     cache.setex(key,60*60*24*30,"haibao/"+ticketId+versiion+".jpg");
            renderJson("haibao/"+ticketId+versiion+".jpg");

//        }else {
//            renderJson(cacheResult);
//        }

    }
    /**
     * 查看可用优惠券
     */
    public void availableCoupons(){
        String ticketId=getPara("ticketId");//商品Id
        String memberId=getPara("memberId");//会员Id
        String money=getPara("money");//钱
        ReturnData returnData=appletService.availableCoupons(ticketId,memberId,money);
        renderJson(returnData);
    }

    /**
     * 升级会员
     */
    public void upgradeMember(){
        String parentId=getPara("parentId");
        String memberId=getPara("memberId");
        ReturnData returnData=appletService.upgradeMember(parentId,memberId);
        renderJson(returnData);

    }
    /**
     * 微信退款
      */

    public void refundment(String orderId) {
        ReturnData returnData=new ReturnData();
        //当前请求地址

        Record wxconfig=appletService.getWxaConfig("4b648bbc537e4cc19942827a2a9dc8d4");
        //退款的订单号
//        String orderId=getPara("orderId");
        Record order=appletService.getOrderInfoService(orderId);
        if("1".equals(String.valueOf(order.get("deliverystatus"))) ){
            returnData.setMsg("订单已发货，无法退款");
            returnData.setResult(false);
            renderJson(returnData);
        }
        Map<String, String> refund = new HashMap<String, String>();
        refund.put("appid",String.valueOf(wxconfig.get("appId")) );//公众账号ID
        refund.put("mch_id", String.valueOf(wxconfig.get("mchId")));//商户号
        refund.put("nonce_str",System.currentTimeMillis() / 1000L + "");//随机字符串
        refund.put("out_trade_no",orderId);//商户订单号
        refund.put("out_refund_no",orderId);//商户退款订单号
        refund.put("total_fee",String.valueOf(CompuUtils.multiply(String.valueOf( order.get("money") ),"100").intValue()));//订单金额
        refund.put("refund_desc","就是想退款");//退款原因
        refund.put("refund_fee",String.valueOf(CompuUtils.multiply(String.valueOf( order.get("money") ),"100").intValue()));//退款金额
        refund.put("notify_url", "https://weixin.qq.com/notify/");//微信回调通知地址,可以使用自己定义也可以使用回调到指定的位置这里使用的是自定义可以在回调中添加一些功能
        String sign = PaymentKit.createSign(refund, "" + "");//map+密钥
        refund.put("sign",sign);//签名
        //退款方法,这个map也是退款结果返回的map只可用于作为判断是否正确的
        String apiclientPath= GlobalParameter.apiclientPath
                +wxconfig.getStr("mchId")+"/apiclient_cert.p12";
        Map<String,String> result =  this.refunds(refund,String.valueOf(wxconfig.get("payKey")), apiclientPath);//map
        //状态码校验格式是否正确，Success是正确的
        if(result.get("return_code").equals("SUCCESS")){
            //退款的结果这是一个map
            if("SUCCESS".equals(result.get("result_code"))){
                System.out.println(JsonUtils.toJson(result));

                //退款申请成功
                System.out.println("退款成功");
                //改变订单状态

                order.remove("state");
                order.set("state","4");
                Db.update("yx_order",order);
                String memberId=order.get("memberId");
                String sql="SELECT * FROM yx_member WHERE id='"+memberId+"'";
                Record memberInfo=Db.findFirst(sql);

                appletService.sendOrderRefundTemplate(memberInfo,order);

                returnData.setResult(true);
                renderJson(returnData);

            }else if("FAIL".equals(result.get("result_code"))){
                renderText(result.get("result_code"));
                return;
            }
        }else if("FAIL".equals(result.get("return_code"))){
            String return_msg = result.get("return_msg");//返回信息
            //失败
            System.out.println(return_msg);
            renderText(return_msg);
            return ;

        }
    }

    /**
     * 退款回调方法
     */
    @Before(Tx.class)
    public void callback() {

        Record wxconfig=appletService.getWxaConfig("4b648bbc537e4cc19942827a2a9dc8d4");
        String xmlMsg = HttpKit.readData(getRequest());
        Map<String,String> params=new HashMap<>();
        org.dom4j.Document result ;
        try {
            result =  DocumentHelper.parseText(xmlMsg);
            Element rootElt = result.getRootElement(); // 获取根节点
            List<Element> list = rootElt.elements();//获取根节点下所有节点
            for (Element element : list) {  //遍历节点
                params.put(element.getName(), element.getText()); //节点的name为map的key，text为map的value
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(params);
        String return_code=params.get("return_code");
        String appid=params.get("appid");
        String mch_id=params.get("mch_id");
        String req_info=params.get("req_info");//回调加密字段
        try {
//            System.out.println(decryptData(req_info));//这里就是解密以后的req_info

        } catch (Exception e) {
            e.printStackTrace();
        }
        String keyMd5 = HashKit.md5(String.valueOf(wxconfig.get("payKey"))).toLowerCase();
        renderJson();
    }





    /**
     * 申请退款，内部添加了随机字符串nonce_str和签名sign
     * @param params 参数map，内部添加了随机字符串nonce_str和签名sign
     * @param paternerKey 商户密钥
     * @param certPath 证书文件目录
     * @return  map
     */

    public static Map<String, String> refunds(Map<String, String> params, String paternerKey, String certPath) {
        params.put("nonce_str", System.currentTimeMillis() + "");
        String sign = PaymentKit.createSign(params, paternerKey);
        params.put("sign", sign);
        String partner = params.get("mch_id");
        String xmlStr = HttpUtils.postSSL(WxpayReturn.REFUND_PAY, PaymentKit.toXml(params), certPath, partner);

        Map<String, String> map = new HashMap<String, String>();
        Document result = null;
        try {
            result = (Document) DocumentHelper.parseText(xmlStr);
            Element rootElt = (Element) result.getRootElement(); // 获取根节点
            List<Element> list = rootElt.elements();//获取根节点下所有节点
            for (Element element : list) {  //遍历节点
                map.put(element.getName(), element.getText()); //节点的name为map的key，text为map的value
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 小程序申请退款
     */
    public void addapplyRefund(){
        Map<String,String[]> map=getParaMap();


        ReturnData returnData=appletService.addapplyRefund(map);

        renderJson(returnData);

    }

    /**
     * 审核退款申请
     */
    public  void editapplyRefund(){
        Map<String,String[]> map=getParaMap();
        ReturnData returnData=orderService.editapplyRefund(map);
        String state=map.get("sta")[0];
        String orderId=map.get("orderId")[0];
        //审核通过执行退款逻辑
        if("1".equals(state)){
            this.refundment(orderId);
        }
        renderJson(returnData);

    }
    /**
     * 商户二维码
     */
    public void qrcoreImg(){
        String shopId=getPara("shopId");
        String sql="SELECT qRcodeimg FROM shop WHERE  id='"+shopId+"'";
        renderJson(Db.queryStr(sql));

    }

    public void forwardReceiveCou(){


    }

    /**
     * 关于我们，客服电话
     */
    public void aboutUs(){
        String shopId=getPara("shopId");
        String element=getPara("element");
        String sql="SELECT "+element+" FROM shop WHERE  id='"+shopId+"'";
        renderJson(Db.queryStr(sql));
    }

    /**
     * 购买成功，领取的优惠券
     */
    public void successBayCou(){
        String memberId=getPara("memberId");
//        memberId="e9b00afbb46f02";
        Record memberinfo=appletService.getMemberInfoById(memberId);
        ReturnData returnData=appletService.payCoupon(memberinfo);
        renderJson(returnData);
    }
    /**
     * 下级会员
     */
    public void juniorMember(){

        String parentId=getPara("parentId");

        int page=getParaToInt("page");

        ReturnData returnData =appletService.juniorMemberService(page,parentId);

        renderJson(returnData);
    }

}

